/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AppAddDevice.java
 *
 * Created on Oct 28, 2011, 12:32:30 PM
 */
package snmpapplication.gui;

import java.awt.event.KeyEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import snmpapplication.Main;
import snmpapplication.beans.Ip;
import snmpapplication.beans.ManagedDevice;
import snmpapplication.log.Severity;
import snmpapplication.observer.DeviceListener;
import snmpapplication.observer.DeviceSubject;
import snmpapplication.utils.DevicesManager;
import snmpapplication.utils.Ping;

/**
 *
 * @author APetcu
 */
public class AppAddDevice extends javax.swing.JFrame implements DeviceSubject {

    /** Creates new form AppAddDevice */
    public AppAddDevice() {

        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Add new device");
        setResizable(false);

        jLabel1.setText("IP address:");

        jButton1.setText("Add");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Cancel");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jTextField1.setColumns(15);
        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(25, 25, 25)
                        .addComponent(jButton1)
                        .addGap(44, 44, 44)
                        .addComponent(jButton2)))
                .addContainerGap(41, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(28, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        makeAdd();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextField1KeyReleased
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            makeAdd();
        }
    }//GEN-LAST:event_jTextField1KeyReleased
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    @Override
    public void notifyObs() {

        for (DeviceListener dl : obs) {
            dl.addedDevice();
        }

    }

    @Override
    public void addDeviceListener(DeviceListener cl) {
        obs.add(cl);
    }

    private void addingDev() {

        boolean ans = DevicesManager.addDevice(new ManagedDevice(new Ip(jTextField1.getText().trim())));

        if (ans) {
            notifyObs();
            Main.log.log(new Severity(Severity.SEV_INFO), "Device added");

            dispose();
        } else {
            JOptionPane.showMessageDialog(null, "Error while adding device", "Error!", JOptionPane.ERROR_MESSAGE);
            jTextField1.setText("");
            Main.log.log(new Severity(Severity.SEV_MIN), "Error while adding new device!");

        }

    }

    private void makeAdd() {
        try {
            AppMainWindow.rs.sleep(300);
            AppMainWindow.sleep(300);
        } catch (InterruptedException ex) {
            Logger.getLogger(AppAddDevice.class.getName()).log(Level.SEVERE, null, ex);
        }

        if (Ip.isValidIp(jTextField1.getText())) {

            boolean pingResp = Ping.pingMe(jTextField1.getText());

            // ping the device
            if (pingResp) {
                    addingDev();
            } else {

                int r = JOptionPane.showConfirmDialog(null, "Device not reachable by Ping. Continue?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);

                if (r == 0) {
                    addingDev();
                    Main.log.log(new Severity(Severity.SEV_MED), "Continue adding device without ping");
                } else {
                    jTextField1.setText("");
                }
            }

        } else {
            JOptionPane.showMessageDialog(null, "Not a valid IP address (X.X.X.X where 0<=X<=255)", "Error!", JOptionPane.ERROR_MESSAGE);
            Main.log.log(new Severity(Severity.SEV_MED), "Not a valid IP address inserted");
            jTextField1.setText("");
        }


    }
}
